package top.haichi.webpaper.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;

import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.haichi.webpaper.entity.*;

import top.haichi.webpaper.mapper.MessageMapper;
import top.haichi.webpaper.mapper.PaperMapper;
import top.haichi.webpaper.mapper.StudentMapper;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;


@RestController
@Slf4j
public class TeacherController {
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private MessageMapper messageMapper;

//    /**
//     * 新建老师信息接口
//     *
//     * @param teacher
//     * @return
//     */
//    @PostMapping("/teacher/add")
//    public Result addTeacher(@RequestBody Teacher teacher) {
//        return teacherService.addTeacher(teacher);
//    }
//
//    /**
//     * 查询老师接口
//     *
//     * @param teacher
//     * @return
//     */
//    @PostMapping("/teacher/get")
//    public Result getTeacher(@RequestBody Teacher teacher) {
//        return teacherService.getTeacher(teacher);
//    }
//
//    /**
//     * 获取老师头像接口
//     *
//     * @param teacher
//     * @return
//     */
//    @PostMapping(value = "/teacher/portrait", produces = MediaType.IMAGE_JPEG_VALUE)
//    public byte[] getPortrait(@RequestBody Teacher teacher, HttpServletResponse response) {
//
//        return teacherService.getPortrait(teacher, response);
//    }
//
//    /**
//     * 更新老师信息
//     *
//     * @param teacher
//     * @return
//     */
//    @PostMapping("/teacher/update")
//    public Result updateTeacher(@RequestBody Teacher teacher) {
//        return teacherService.updateTeacher(teacher);
//    }
//
//    /**
//     * 老师签字
//     *
//     * @return
//     */
//    @PostMapping("/teacher/sign")
//    public Result signPaper() {
//        return null;
//    }

    /**
     * 老师查询论文
     */
    @PostMapping("/teacher/getpapers")
    public Result getPapers(@RequestBody JsonNode jsonNode) {
        String id = jsonNode.get("id").asText();
        Student student = studentMapper.selectById(id);
        HashMap<String, Object> classMap = new HashMap<>();
        classMap.put("class_name", student.getClassName());
//        classMap.put("title", jsonNode.get("keyWords").asText());
        List<Student> students = studentMapper.selectByMap(classMap);
        ArrayList<String> strings = new ArrayList<>();
        for (Student student1 : students) {
            strings.add(student1.getId());
        }
        QueryWrapper<Paper> wrapper = new QueryWrapper<>();
        wrapper.in("owner_id", strings)
                .like("title", jsonNode.get("keyWords").asText());
        List<Paper> papers = paperMapper.selectList(wrapper);
        return Result.success("获取成功", papers);
    }

//    /**
//     * 老师搜索论文
//     *
//     * @return
//     */
//    @PostMapping("/teacher/searchpapers")
//    public Result searchPaperByTeacher(@RequestBody JsonNode jsonNode) {
//        QueryWrapper<Paper> wrapper = new QueryWrapper<>();
//        wrapper.like("title", jsonNode.get("keyWord").asText());
//        wrapper.eq("teacher_id", jsonNode.get("id").asText());
//        List<Paper> papers = paperMapper.selectList(wrapper);
//        if (!papers.isEmpty()) {
//            return Result.success("查询成功", papers);
//        } else {
//            return Result.error("没有查询到结果");
//        }
//    }

//    /**
//     * 下载论文
//     *
//
//     * @return
//     */
//    @PostMapping(value = "/teacher/downloadpaperbyuuid",produces = MediaType.APPLICATION_PDF_VALUE)
//    public byte[] getPaperByUUID(@RequestBody JsonNode jsonNode) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("uuid",jsonNode.get("uuid").asText());
//        map.put("teacher_id",jsonNode.get("id").asText());
//        try {
//            Paper paper = paperMapper.selectByMap(map).get(0);
////            new File(FileUtils.getUploadPath());
//            return null;
//        }catch (Exception e){
//            return null;
//        }
//    }

//    private class teacherKeyword{
//        private Teacher teacher;
//        private String keyWord;
//
//        public teacherKeyword() {
//        }
//
//        public teacherKeyword(Teacher teacher, String keyWord) {
//            this.teacher = teacher;
//            this.keyWord = keyWord;
//        }
//
//
//    }

    /**
     * 老师修改论文状态
     *
     * @param
     * @return
     */
    @PostMapping("/teacher/setstatus")
    public Result setStatus(@RequestBody Paper paper) {
        String paperId = paper.getId();
        String status = paper.getStatus();
        if (!(status.equals("审核中") || status.equals("待修改") || status.equals("已完成"))) {
            return Result.error("你干嘛");
        } else {
            //没校验论文是不是自己学生的qaq
            Paper selectedPaper = paperMapper.selectById(paperId);
            selectedPaper.setStatus(status);
            paperMapper.updateById(selectedPaper);
            return Result.success("修改成功!");
        }
    }

    /**
     * 老师查询学生
     *
     * @param
     * @return
     */
    @PostMapping("/teacher/getstudents")
    public Result getStudents(@RequestBody Teacher teacher) {
        String id = teacher.getId();
        Student selectedTeacher = studentMapper.selectById(id);
        String className = selectedTeacher.getClassName();
        HashMap<String, Object> map = new HashMap<>();
        map.put("class_name", className);
        List<Student> students = studentMapper.selectByMap(map);
        HashMap<String, String> resultMap = new HashMap<>();
        for (Student student : students) {
            resultMap.put(student.getRealName(), student.getId());
        }
        return Result.success("查询成功", resultMap);
    }

    @PostMapping("/teacher/sendmessage")
    public Result sendMessage(@RequestBody JsonNode jsonNode) {
        String teacherId = jsonNode.get("id").asText();
        String title = jsonNode.get("title").asText();
        String content = jsonNode.get("content").asText();
        content = filterTags(content);
        LocalDate created = LocalDate.now();
        Student selectedStudent = studentMapper.selectById(teacherId);
        String from = selectedStudent.getName() + "|" + selectedStudent.getRealName();
        try {
            for (JsonNode node : jsonNode.get("target")) {
                String id = UUID.randomUUID().toString();
                String to = node.asText();
                Message message = new Message(title, true, content, id, created, from, to);
                messageMapper.insert(message);
            }
            String id = UUID.randomUUID().toString();
            String to = teacherId;
            Message message = new Message(title, true, content, id, created, from, to);
            messageMapper.insert(message);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发送失败");
        }
        return Result.success("发送成功");
    }

    //不完美，有办法注入
        public static String filterTags(String html) {
            String regex = "<(?!/?img(\\s|>|$)|/?a(\\s|>|$)|/?b(\\s|>|$)|/?i(\\s|>|$))[^>]*>";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(html);
            return matcher.replaceAll("");
        }
}